class LogSystem {
    constructor() {
        this.currentPage = 1;
        this.pageSize = 20;
        this.currentTab = 'all';
        this.filters = {
            startTime: '',
            endTime: '',
            logType: '',
            keyword: '',
            ipAddress: '',
            country: ''
        };
        this.logsData = [];
        this.init();
    }

    // 初始化系统
    init() {
        this.setupEventListeners();
        this.loadInitialData();
        this.setDefaultDateRange();
    }

    // 设置事件监听器
    setupEventListeners() {
        // 输入框实时搜索
        document.getElementById('keyword').addEventListener('input', 
            this.debounce(() => this.searchLogs(), 500)
        );
        
        // 筛选条件变化
        ['logType', 'ipAddress', 'country'].forEach(id => {
            document.getElementById(id).addEventListener('change', () => this.searchLogs());
        });
        
        // 时间范围变化
        ['startTime', 'endTime'].forEach(id => {
            document.getElementById(id).addEventListener('change', () => this.searchLogs());
        });
    }

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 设置默认时间范围（今日）
    setDefaultDateRange() {
        this.setDateRange('today');
    }

    // 设置时间范围
    setDateRange(range, event = null) {
        const now = new Date();
        let startTime, endTime;

        switch (range) {
            case 'today':
                startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate());
                endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
                break;
            case 'yesterday':
                startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
                endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate());
                break;
            case '7days':
                startTime = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                endTime = now;
                break;
            case '30days':
                startTime = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
                endTime = now;
                break;
        }

        // 更新按钮状态
        document.querySelectorAll('.quick-date-btn').forEach(btn => btn.classList.remove('active'));
        if (event && event.target) {
            event.target.classList.add('active');
        }

        // 设置时间输入框
        document.getElementById('startTime').value = this.formatDateTimeLocal(startTime);
        document.getElementById('endTime').value = this.formatDateTimeLocal(endTime);

        this.searchLogs();
    }

    // 格式化日期时间为本地格式
    formatDateTimeLocal(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}`;
    }

    // 加载初始数据
    async loadInitialData() {
        try {
            // 模拟API调用
            await this.fetchLogs();
            this.updateStatistics();
        } catch (error) {
            console.error('加载日志数据失败:', error);
            this.showError('加载日志数据失败，请刷新页面重试');
        }
    }

    // 搜索日志
    async searchLogs() {
        this.currentPage = 1;
        await this.fetchLogs();
    }

    // 获取筛选条件
    getFilterParams() {
        return {
            page: this.currentPage,
            pageSize: this.pageSize,
            tab: this.currentTab,
            startTime: document.getElementById('startTime').value,
            endTime: document.getElementById('endTime').value,
            logType: document.getElementById('logType').value,
            keyword: document.getElementById('keyword').value,
            ipAddress: document.getElementById('ipAddress').value,
            country: document.getElementById('country').value
        };
    }

    // 获取日志数据
    async fetchLogs() {
        try {
            const params = this.getFilterParams();
            
            // 使用真实API调用
            const response = await this.fetchRealLogs(params);
            
            this.logsData = response.data.logs;
            this.renderLogs();
            this.renderPagination(response.data.total, response.data.totalPages);
            this.updateStatistics();
            
        } catch (error) {
            console.error('获取日志数据失败:', error);
            this.showError('获取日志数据失败，请检查网络连接');
        }
    }

    // 获取真实日志数据
    async fetchRealLogs(params) {
        try {
            const queryParams = new URLSearchParams();
            Object.keys(params).forEach(key => {
                if (params[key]) {
                    // 确保参数编码正确
                    const encodedValue = encodeURIComponent(params[key]);
                    queryParams.append(key, encodedValue);
                }
            });
            
            const response = await fetch(`/api/logs?${queryParams}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8',
                    'Authorization': `Bearer ${localStorage.getItem('authToken') || ''}`
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            // 确保响应编码正确
            const text = await response.text();
            const result = JSON.parse(text);
            
            if (result.success) {
                return result;
            } else {
                throw new Error(result.message || '获取日志数据失败');
            }
        } catch (error) {
            console.error('获取日志数据失败:', error);
            throw new Error('无法连接到日志数据服务，请检查网络连接');
        }
    }


            const actionList = actions[type];
            const action = actionList[Math.floor(Math.random() * actionList.length)];
            
            // 生成随机时间（过去30天内）
            const timestamp = new Date(now.getTime() - Math.random() * 30 * 24 * 60 * 60 * 1000);
            
            logs.push({
                id: `log_${i + 1}`,
                timestamp: timestamp.toISOString(),
                type: type,
                action: action,
                ip: `192.168.${Math.floor(Math.random() * 255)}.${Math.floor(Math.random() * 255)}`,
                country: countries[Math.floor(Math.random() * countries.length)],
                device: devices[Math.floor(Math.random() * devices.length)],
                username: type === 'auth' ? `user${Math.floor(Math.random() * 1000)}@example.com` : '',
                status: statuses[Math.floor(Math.random() * statuses.length)],
                details: {
                    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                    referer: 'https://example.com',
                    sessionId: `session_${Math.random().toString(36).substr(2, 9)}`,
                    responseTime: Math.floor(Math.random() * 1000) + 'ms'
                }
            });
        }
        
        // 按时间倒序排序
        return logs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    }

    // 渲染日志列表
    renderLogs() {
        const container = document.getElementById('logs-container');
        
        if (this.logsData.length === 0) {
            container.innerHTML = `
                <div style="text-align: center; padding: 40px; color: #666;">
                    <i class="fas fa-search" style="font-size: 48px; margin-bottom: 20px;"></i>
                    <p>暂无符合条件的日志记录</p>
                </div>
            `;
            return;
        }
        
        const logsHtml = this.logsData.map(log => this.renderLogItem(log)).join('');
        container.innerHTML = logsHtml;
    }

    // 渲染单个日志项
    renderLogItem(log) {
        const time = new Date(log.timestamp).toLocaleString('zh-CN');
        const typeClass = `type-${log.type}`;
        
        return `
            <div class="log-item" data-log-id="${log.id}">
                <div class="log-time" data-label="时间">${time}</div>
                <div data-label="操作内容">
                    <span class="log-type ${typeClass}">${this.getTypeLabel(log.type)}</span>
                    ${log.action}
                    ${log.status === 'error' ? '<span style="color: #e74c3c; margin-left: 5px;">[错误]</span>' : ''}
                    ${log.status === 'warning' ? '<span style="color: #f39c12; margin-left: 5px;">[警告]</span>' : ''}
                </div>
                <div class="log-ip" data-label="IP地址">${log.ip}</div>
                <div class="log-country" data-label="国家/地区">
                    <img src="https://flagcdn.com/w20/${log.country.toLowerCase()}.png" 
                         class="flag-icon" alt="${log.country}">
                    ${this.getCountryName(log.country)}
                </div>
                <div class="log-device" data-label="设备类型">${log.device}</div>
                <div class="log-actions" data-label="操作">
                    <button class="action-btn" onclick="logSystem.viewLogDetail('${log.id}')">
                        <i class="fas fa-eye"></i> 查看
                    </button>
                    <button class="action-btn" onclick="logSystem.exportSingleLog('${log.id}')">
                        <i class="fas fa-download"></i> 导出
                    </button>
                </div>
            </div>
        `;
    }

    // 获取类型标签
    getTypeLabel(type) {
        const labels = {
            auth: '认证',
            access: '访问',
            business: '业务',
            security: '安全'
        };
        return labels[type] || type;
    }

    // 获取国家名称
    getCountryName(code) {
        const countries = {
            CN: '中国', US: '美国', JP: '日本', DE: '德国',
            GB: '英国', FR: '法国', CA: '加拿大', AU: '澳大利亚'
        };
        return countries[code] || code;
    }

    // 渲染分页
    renderPagination(total, totalPages) {
        const container = document.getElementById('pagination');
        
        if (totalPages <= 1) {
            container.innerHTML = '';
            return;
        }
        
        let paginationHtml = '';
        
        // 上一页
        if (this.currentPage > 1) {
            paginationHtml += `<button class="page-btn" onclick="logSystem.goToPage(${this.currentPage - 1})">上一页</button>`;
        }
        
        // 页码按钮
        const startPage = Math.max(1, this.currentPage - 2);
        const endPage = Math.min(totalPages, startPage + 4);
        
        for (let i = startPage; i <= endPage; i++) {
            const activeClass = i === this.currentPage ? 'active' : '';
            paginationHtml += `<button class="page-btn ${activeClass}" onclick="logSystem.goToPage(${i})">${i}</button>`;
        }
        
        // 下一页
        if (this.currentPage < totalPages) {
            paginationHtml += `<button class="page-btn" onclick="logSystem.goToPage(${this.currentPage + 1})">下一页</button>`;
        }
        
        container.innerHTML = paginationHtml;
    }

    // 跳转到指定页面
    goToPage(page) {
        this.currentPage = page;
        this.fetchLogs();
        // 滚动到顶部
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    // 切换日志标签
    switchLogTab(tab, event = null) {
        this.currentTab = tab;
        this.currentPage = 1;
        
        // 更新标签状态
        document.querySelectorAll('.log-tab').forEach(tabEl => tabEl.classList.remove('active'));
        if (event && event.target) {
            event.target.classList.add('active');
        }
        
        this.fetchLogs();
    }

    // 更新统计信息
    updateStatistics() {
        const counts = { all: 0, auth: 0, access: 0, business: 0, security: 0 };
        const statusCounts = { success: 0, warning: 0, error: 0 };
        const hourlyCounts = Array(24).fill(0);
        let todayCount = 0;
        
        const today = new Date().toDateString();
        
        // 统计各类型日志数量
        this.logsData.forEach(log => {
            counts.all++;
            counts[log.type]++;
            statusCounts[log.status]++;
            
            // 统计小时分布
            const hour = new Date(log.timestamp).getHours();
            hourlyCounts[hour]++;
            
            // 统计今日日志
            const logDate = new Date(log.timestamp).toDateString();
            if (logDate === today) {
                todayCount++;
            }
        });
        
        // 更新标签计数
        Object.keys(counts).forEach(type => {
            const element = document.getElementById(`${type}-count`);
            if (element) {
                element.textContent = counts[type];
            }
        });
        
        // 更新统计卡片
        this.updateStatCards(counts, statusCounts, todayCount);
        
        // 更新图表数据
        this.updateCharts(counts, statusCounts, hourlyCounts);
    }

    // 更新统计卡片
    updateStatCards(counts, statusCounts, todayCount) {
        const statElements = {
            totalLogs: counts.all,
            errorLogs: statusCounts.error,
            securityLogs: counts.security,
            todayLogs: todayCount
        };
        
        Object.keys(statElements).forEach(id => {
            const element = document.getElementById(id);
            if (element) {
                element.textContent = statElements[id];
            }
        });
    }

    // 更新图表数据
    updateCharts(typeCounts, statusCounts, hourlyCounts) {
        // 更新日志类型分布图表
        if (window.logTypeChart) {
            const typeData = [
                { value: typeCounts.auth, name: '用户认证' },
                { value: typeCounts.access, name: '访问日志' },
                { value: typeCounts.business, name: '业务日志' },
                { value: typeCounts.security, name: '安全日志' }
            ];
            
            window.logTypeChart.setOption({
                series: [{
                    data: typeData
                }]
            });
        }
        
        // 更新24小时访问趋势图表
        if (window.hourlyTrendChart) {
            window.hourlyTrendChart.setOption({
                series: [{
                    data: hourlyCounts
                }]
            });
        }
        
        // 更新状态分布图表
        if (window.statusChart) {
            const statusData = [
                { value: statusCounts.success, name: '成功' },
                { value: statusCounts.warning, name: '警告' },
                { value: statusCounts.error, name: '错误' }
            ];
            
            window.statusChart.setOption({
                series: [{
                    data: statusData
                }]
            });
        }
    }

    // 查看日志详情
    viewLogDetail(logId) {
        const log = this.logsData.find(l => l.id === logId);
        if (!log) return;
        
        const modal = document.getElementById('logDetailModal');
        const content = document.getElementById('logDetailContent');
        
        content.innerHTML = this.renderLogDetail(log);
        modal.style.display = 'block';
    }

    // 渲染日志详情
    renderLogDetail(log) {
        return `
            <div class="detail-section">
                <h3>基本信息</h3>
                <div class="detail-grid">
                    <div class="detail-item">
                        <div class="detail-label">日志ID</div>
                        <div class="detail-value">${log.id}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">时间</div>
                        <div class="detail-value">${new Date(log.timestamp).toLocaleString('zh-CN')}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">类型</div>
                        <div class="detail-value">
                            <span class="log-type type-${log.type}">${this.getTypeLabel(log.type)}</span>
                        </div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">操作</div>
                        <div class="detail-value">${log.action}</div>
                    </div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3>访问信息</h3>
                <div class="detail-grid">
                    <div class="detail-item">
                        <div class="detail-label">IP地址</div>
                        <div class="detail-value">${log.ip}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">国家/地区</div>
                        <div class="detail-value">
                            <img src="https://flagcdn.com/w20/${log.country.toLowerCase()}.png" 
                                 style="width: 16px; height: 12px; margin-right: 5px;">
                            ${this.getCountryName(log.country)}
                        </div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">设备信息</div>
                        <div class="detail-value">${log.device}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">用户代理</div>
                        <div class="detail-value">${log.details.userAgent}</div>
                    </div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3>详细信息</h3>
                <div class="detail-item">
                    <div class="detail-label">会话ID</div>
                    <div class="detail-value">${log.details.sessionId}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">响应时间</div>
                    <div class="detail-value">${log.details.responseTime}</div>
                </div>
                <div class="detail-item">
                    <div class="detail-label">来源页面</div>
                    <div class="detail-value">${log.details.referer}</div>
                </div>
            </div>
            
            <div class="detail-section">
                <h3>原始数据</h3>
                <pre style="background: #f8f9fa; padding: 15px; border-radius: 4px; overflow-x: auto;">
${JSON.stringify(log, null, 2)}
                </pre>
            </div>
        `;
    }

    // 导出单个日志
    exportSingleLog(logId) {
        const log = this.logsData.find(l => l.id === logId);
        if (!log) return;
        
        this.exportData([log], `log_${log.id}_${new Date().getTime()}.json`);
    }

    // 导出日志
    exportLogs() {
        if (this.logsData.length === 0) {
            this.showError('没有可导出的日志数据');
            return;
        }
        
        // 在实际项目中，这里应该调用后端导出API
        this.exportData(this.logsData, `logs_export_${new Date().getTime()}.json`);
    }

    // 导出数据到文件
    exportData(data, filename) {
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        this.showSuccess(`日志数据已导出: ${filename}`);
    }

    // 清空筛选条件
    clearFilters() {
        document.getElementById('startTime').value = '';
        document.getElementById('endTime').value = '';
        document.getElementById('logType').value = '';
        document.getElementById('keyword').value = '';
        document.getElementById('ipAddress').value = '';
        document.getElementById('country').value = '';
        
        document.querySelectorAll('.quick-date-btn').forEach(btn => btn.classList.remove('active'));
        
        this.searchLogs();
    }

    // 显示成功消息
    showSuccess(message) {
        this.showMessage(message, 'success');
    }

    // 显示错误消息
    showError(message) {
        this.showMessage(message, 'error');
    }

    // 显示消息
    showMessage(message, type) {
        // 简单的消息提示实现
        const alert = document.createElement('div');
        alert.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 4px;
            color: white;
            z-index: 10000;
            font-weight: bold;
            background: ${type === 'success' ? '#27ae60' : '#e74c3c'};
        `;
        alert.textContent = message;
        
        document.body.appendChild(alert);
        
        setTimeout(() => {
            document.body.removeChild(alert);
        }, 3000);
    }
}

// 全局函数
function closeModal() {
    document.getElementById('logDetailModal').style.display = 'none';
}

function setDateRange(range) {
    logSystem.setDateRange(range, event);
}

function switchLogTab(tab) {
    logSystem.switchLogTab(tab, event);
}

function searchLogs() {
    logSystem.searchLogs();
}

function clearFilters() {
    logSystem.clearFilters();
}

function exportLogs() {
    logSystem.exportLogs();
}

// 点击模态框外部关闭
window.onclick = function(event) {
    const modal = document.getElementById('logDetailModal');
    if (event.target === modal) {
        closeModal();
    }
}

// 初始化日志系统
const logSystem = new LogSystem();